const app = getApp();

Page({
  data: {
    messages: [],
    inputText: '',
    targetUser: {},
    userInfo: {},
    lastMsgId: 0,
    loading: false,
    autoRefresh: true,
    refreshInterval: null
  },

  onLoad(options) {
    console.log('💬 Chat page loaded with options:', options);
    
    this.toUserId = options.toUserId;
    this.toUserName = options.toUserName;
    this.postId = options.postId;
    this.userInfo = app.globalData.userInfo;
    
    console.log('👤 Current user:', this.userInfo);
    console.log('🎯 Target user ID:', this.toUserId);
    
    this.setData({ 
      userInfo: this.userInfo,
      targetUser: {
        _id: this.toUserId,
        username: this.toUserName || '未知用户'
      }
    });
    
    this.loadMessages();
    
    // 设置自动刷新
    this.startAutoRefresh();
    
    // 设置页面标题
    if (this.toUserName) {
      wx.setNavigationBarTitle({
        title: `与 ${this.toUserName} 的对话`
      });
    }
  },

  onShow() {
    console.log('💬 Chat page shown');
    this.loadMessages();
    this.startAutoRefresh();
  },

  onHide() {
    console.log('💬 Chat page hidden');
    this.stopAutoRefresh();
  },

  onUnload() {
    console.log('💬 Chat page unloaded');
    this.stopAutoRefresh();
  },

  startAutoRefresh() {
    // 每5秒自动刷新一次消息
    this.stopAutoRefresh();
    this.refreshInterval = setInterval(() => {
      if (this.data.autoRefresh) {
        console.log('🔄 Auto refreshing messages...');
        this.loadMessages();
      }
    }, 5000);
  },

  stopAutoRefresh() {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
    }
  },

  toggleAutoRefresh() {
    this.setData({
      autoRefresh: !this.data.autoRefresh
    });
    if (this.data.autoRefresh) {
      this.startAutoRefresh();
    } else {
      this.stopAutoRefresh();
    }
  },

  async loadMessages() {
    if (!this.toUserId) {
      console.error('❌ No target user ID');
      return;
    }

    this.setData({ loading: true });
    
    try {
      console.log('📨 Loading messages with user:', this.toUserId);
      const messages = await app.request(`/messages/${this.toUserId}`, 'GET');
      console.log('✅ Messages loaded:', messages ? messages.length : 0);
      
      this.setData({ 
        messages: messages || [],
        lastMsgId: messages && messages.length > 0 ? messages.length - 1 : 0,
        loading: false
      });
      
      // 更新目标用户信息
      if (messages && messages.length > 0) {
        const firstMessage = messages[0];
        let targetUser = null;
        
        if (firstMessage.from && firstMessage.to) {
          targetUser = firstMessage.from._id === this.userInfo.id ? firstMessage.to : firstMessage.from;
        }
        
        if (targetUser) {
          this.setData({ 
            targetUser: {
              _id: targetUser._id,
              username: targetUser.username
            }
          });
          
          // 更新页面标题
          wx.setNavigationBarTitle({
            title: `与 ${targetUser.username} 的对话`
          });
        }
      }
    } catch (error) {
      console.error('❌ Load messages error:', error);
      this.setData({ loading: false });
    }
  },

  onInput(e) {
    this.setData({ inputText: e.detail.value });
  },

  async onSend() {
    const content = this.data.inputText.trim();
    if (!content) {
      wx.showToast({ title: '消息不能为空', icon: 'none' });
      return;
    }

    if (!this.toUserId) {
      wx.showToast({ title: '无法发送消息', icon: 'none' });
      return;
    }

    console.log('📤 Sending message to:', this.toUserId, 'content:', content);

    try {
      const message = await app.request('/messages', 'POST', {
        to: this.toUserId,
        content: content,
        postId: this.postId
      });

      console.log('✅ Message sent successfully:', message);
      
      // 添加到消息列表
      const newMessages = [...this.data.messages, message];
      this.setData({
        messages: newMessages,
        inputText: '',
        lastMsgId: newMessages.length - 1
      });

    } catch (error) {
      console.error('❌ Send message error:', error);
      wx.showToast({ title: '发送失败: ' + (error.error || '未知错误'), icon: 'none' });
    }
  },

  onRefresh() {
    console.log('🔄 Manual refresh');
    this.loadMessages();
  },

  formatTime(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
});